package com.demo.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

public class HttpClientUtils {

    public static void main(String[] args){
        String address = HttpClientUtils.findByLatAndLng("51.132573", "124.802554");
        System.out.println("地址是: " + address);
    }

    //传入经纬度, 返回查询的地区, lng: 纬度, lat: 经度
    public static String findByLatAndLng(String lng, String lat) {
        try {
            //移除坐标前后的 空格
            /*lng = lng.trim();
            lat = lat.trim();*/

            CloseableHttpClient httpClient = HttpClients.createDefault();
            // url中的ak值要替换成自己的:
            String url = "http://gc.ditu.aliyun.com/regeocoding?l="+lat+","+lng+"&type=010";
            //System.out.println(url);
            HttpGet httpGet = new HttpGet(url);

            CloseableHttpResponse response = httpClient.execute(httpGet);

            HttpEntity httpEntity = response.getEntity();

            String json = EntityUtils.toString(httpEntity);

            Map<String, Object> result = JSONObject.parseObject(json, Map.class);
            if (result.get("status").equals(0)) {
                Map<String, Object> resultMap = (Map<String, Object>) result.get("result");
                resultMap = (Map<String, Object>) resultMap.get("addressComponent");
                String country = (String) resultMap.get("country");
                String province = (String) resultMap.get("province");
                String city = (String) resultMap.get("city");
                return country + province + city;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}